var express = require("express");
var router = express.Router();
const lowdb = require("lowdb");
const FileSync = require("lowdb/adapters/FileSync");
const shortid = require("shortid");
const adapter = new FileSync(__dirname + "/" + "../data/db.json");

// 获取 db 对象
const db = lowdb(adapter);

// 初始化数据
/* db.defaults({
  accounts: [],
}).write(); */

// 记账本列表
router.get("/account", function(req, res, next) {
  let accounts = db.get("accounts").value();
  console.log(accounts);
  res.render("list", { accounts: accounts });
});

// 添加记录
router.get("/account/create", (req, res, next) => {
  res.render("create");
});

router.post("/account", (req, res) => {
  // console.log(req.body);
  // 生成 id
  let id = shortid.generate();
  db.get("accounts")
    // .push({
    .unshift({
      id: id,
      ...req.body,
    })
    .write();
  // res.send("添加记录");
  msg = "添加成功";
  url = "/account";
  res.render("success", {
    msg: msg,
    url: url,
  });
});

// 删除记录
router.get("/account/:id", (req, res) => {
  // 获取 id
  let id = req.params.id;
  db.get("accounts")
    .remove({
      id: id,
    })
    .write();
  // 提醒
  // res.send("删除成功");
  msg = "删除成功";
  url = "/account";
  res.render("success", {
    msg: msg,
    url: url,
  });
});

module.exports = router;
